package com.gyj.zookeeper.Watcher;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * Created by Gao on 2018/10/22.
 */
public class Test {

    private static void test() throws IOException, KeeperException, InterruptedException {
        ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 30000, new TestWatcher());
        String node = "/node3";
        //判断节点是否存在
        Stat stat = zk.exists(node, false);
        if (stat == null) {
            //创建节点
            String createResult = zk.create(node, "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("创建节点：" + createResult);  //创建节点：/node1
        }
        byte[] data = zk.getData(node, false, stat);
        System.out.println("拿到数据：" + new String(data));  //拿到数据：test
        zk.close();
    }

    public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
        test();
    }

    private static class TestWatcher implements Watcher {
        public void process(WatchedEvent arg0) {
            System.out.println("***************");
            System.out.println("path:" + arg0.getPath());
            System.out.println("type:" + arg0.getType());
            System.out.println("state:" + arg0.getState());
        /*path:null
        type:None
        state:SyncConnected*/
        }
    }
}
